<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="主键ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单所属日期" prop="orderBelongDate">
        <el-date-picker
          clearable
          v-model="queryParams.orderBelongDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择订单所属日期"
        >
        </el-date-picker>
      </el-form-item>



      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bulkegg:orderfilerecord:add']"
        >新增</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bulkegg:orderfilerecord:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bulkegg:orderfilerecord:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bulkegg:orderfilerecord:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="openUpload = true"
        >
          上传压缩包
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderfilerecordList"
      @selection-change="handleSelectionChange"
      style="overflow-x: scroll;"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column
        label="原始压缩包文件名"
        align="center"
        prop="originPath"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ getFileName(scope.row.originPath) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="处理后文件夹名"
        align="center"
        prop="targetPath"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ getFileName(scope.row.targetPath) }}</span>
        </template>
      </el-table-column>

    


      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"      
      />

      <el-table-column
        label="供应关系公司ID"
        align="center"
        prop="supplyRelationCompanyId"
      />

      

      <el-table-column
        label="供货方"
        align="center"
        prop="supplierCompany"
        width="120"
      />
      <el-table-column
        label="贸易商"
        align="center"
        prop="traderCompany"
        width="120"
      />
      <el-table-column
        label="采购方"
        align="center"
        prop="buyerCompany"
        width="120"
      />
      <el-table-column
        label="给贸易商的包装运输单价"
        align="center"
        prop="upstreamDiff"
        width="180"
      />
      <el-table-column
        label="给采购方的包装运输单价"
        align="center"
        prop="downstreamDiff"
        width="180"
      />

        <el-table-column
        label="订单馆陶价格"
        align="center"
        prop="orderGuantaoPrice"
      />
      <el-table-column
        label="订单所属日期"
        align="center"
        prop="orderBelongDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderBelongDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bulkegg:orderfilerecord:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bulkegg:orderfilerecord:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownloadZip(scope.row.originPath)"
            v-hasPermi="['bulkegg:orderfilerecord:download']"
            >下载原始文件</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownloadZip(scope.row.targetPath)"
            v-hasPermi="['bulkegg:orderfilerecord:download']"
            >下载处理后文件</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商订单处理记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原始压缩包绝对路径" prop="originPath">
          <el-input
            v-model="form.originPath"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="处理后文件夹绝对路径" prop="targetPath">
          <el-input
            v-model="form.targetPath"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="订单馆陶价格" prop="orderGuantaoPrice">
          <el-input
            v-model="form.orderGuantaoPrice"
            placeholder="请输入订单馆陶价格"
          />
        </el-form-item>
        <el-form-item label="订单所属日期" prop="orderBelongDate">
          <el-date-picker
            clearable
            v-model="form.orderBelongDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择订单所属日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应关系公司ID" prop="supplyRelationCompanyId">
          <el-input
            v-model="form.supplyRelationCompanyId"
            placeholder="请输入供应关系公司ID"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 2. 回显区域（可选） -->
    <el-card v-if="result" header="服务端返回" style="margin-top: 15px">
      <pre>{{ JSON.stringify(result, null, 2) }}</pre>
    </el-card>

    <!--上传压缩包弹窗页面 -->
    <el-dialog
      title="上传压缩包并处理 Excel"
      :visible.sync="openUpload"
      width="520px"
      append-to-body
      :close-on-click-modal="false"
      @closed="uploadReset"
    >
      <!-- 上传区域 -->
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        action=""
        :limit="1"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :file-list="fileList"
        :on-change="onChange"
        :on-exceed="onExceed"
        :http-request="uploadRequest"
        accept=".zip,.rar,.7z"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
        <div slot="tip" class="el-upload__tip">
          仅支持 zip/rar/7z，且不超过 100MB
        </div>
      </el-upload>

      <!-- 进度条 -->
      <div v-if="percent > 0" style="margin-top: 15px">
        <el-progress :percentage="percent" :stroke-width="12" />
      </div>

      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="uploadCancel">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submit"
          >开 始 上 传</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrderfilerecord,
  getOrderfilerecord,
  delOrderfilerecord,
  addOrderfilerecord,
  updateOrderfilerecord,
  uploadZip,
  downloadZip,
} from "@/api/bulkegg/orderfilerecord";

export default {
  name: "Orderfilerecord",
  data() {
    return {
      openUpload: false, // 上传压缩包弹窗开关
      loading: false, // 上传中传压缩包
      percent: 0, // 进度
      fileList: [], // el-upload 文件列表
      result: null, // 服务端回包
      // 遮罩层
      listloading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商订单处理记录表格数据
      orderfilerecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        orderBelongDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        originPath: [
          {
            required: true,
            message: "原始压缩包绝对路径不能为空",
            trigger: "blur",
          },
        ],
        targetPath: [
          {
            required: true,
            message: "处理后文件夹绝对路径不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 提取文件名 */
    getFileName(filePath) {
      if (!filePath) return "";
      // 处理Windows和Unix路径分隔符
      const lastSlash = Math.max(
        filePath.lastIndexOf("/"),
        filePath.lastIndexOf("\\")
      );
      return lastSlash !== -1 ? filePath.substring(lastSlash + 1) : filePath;
    },
    /** 查询供应商订单处理记录列表 */
    getList() {
      this.listloading = true;
      listOrderfilerecord(this.queryParams).then((response) => {
        this.orderfilerecordList = response.rows;
        this.total = response.total;
        this.listloading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        originPath: null,
        targetPath: null,
        orderGuantaoPrice: null,
        orderBelongDate: null,
        supplyRelationCompanyId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商订单处理记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrderfilerecord(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改供应商订单处理记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderfilerecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderfilerecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除供应商订单处理记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrderfilerecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "bulkegg/orderfilerecord/export",
        {
          ...this.queryParams,
        },
        `orderfilerecord_${new Date().getTime()}.xlsx`
      );
    },
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) this.$message.error("大小不能超过 100MB!");
      return isLt100M;
    },
    onSuccess(res) {
      this.$message.success(res.msg || "处理完成");
      this.loading = false;
      this.$message.success(res.msg || "处理完成");
      this.result = res; // 当前页就能拿到返回值
      this.cancel();
      // 这里可以继续：刷新表格、调用下载、跳转详情等
      this.$refs.upload.clearFiles();
    },
    /* -------- upload 相关 -------- */
    onChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    onExceed() {
      this.$message.warning("最多上传 1 个文件");
    },
    // 自定义上传
    uploadRequest(param) {
      const fd = new FormData();
      fd.append("file", param.file);
      // 1. 显示上传进度
      return uploadZip(fd, {
        onUploadProgress: (e) => {
          this.percent = Math.round((e.loaded / e.total) * 100);
        },
      })
        .then((res) => {
          // 2. 成功后手动触发 el-upload 的 onSuccess，这样外部 @success 才能收到
          param.onSuccess(res);
          this.getList(); //刷新最外层列表
          this.openUpload = false;
        })
        .catch((err) => {
          // 3. 失败后触发 el-upload 的 onError
          param.onError(err);
        });
    },
    // 提交
    submit() {
      if (!this.fileList.length) {
        this.$message.warning("请先选择文件");
        return;
      }
      this.loading = true;
      this.percent = 0;
      this.$refs.upload.submit();
    },
    // 失败回调
    onError(err) {
      this.loading = false;
      this.$message.error(err.message || "上传失败");
    },
    // 关闭弹窗 & 重置
    uploadCancel() {
      this.openUpload = false;
    },
    uploadReset() {
      this.fileList = [];
      this.loading = false;
      this.percent = 0;
      this.$refs.upload.clearFiles();
    },
    /** 下载文件中 */
    handleDownloadZip(zipFileName) {
      if (!zipFileName) {
        this.$message.warning('文件路径不能为空')
        return
      }

      this.$modal.loading('正在下载文件，请稍候...')

      downloadZip(zipFileName)
        .then(response => {
          const filename = this.getFileName(zipFileName)

          let headerFilename = null
          const contentDisposition = response.headers
            ? response.headers['content-disposition']
            : null
          if (contentDisposition) {
            const matches = contentDisposition.match(/filename="?([^"]+)"?/)
            if (matches && matches[1]) {
              headerFilename = decodeURIComponent(
                matches[1].replace(/%22/g, '')
              )
            }
          }

          const blob = response instanceof Blob ? response : new Blob([response.data || response], { type: 'application/zip' })
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = headerFilename || filename || 'download.zip'
          link.style.display = 'none'

          document.body.appendChild(link)
          link.click()

          this.$nextTick(() => {
            document.body.removeChild(link)
            URL.revokeObjectURL(link.href)
          })

          this.$message.success('下载成功')
        })
        .catch(error => {
          console.error('下载失败:', error)
          let errorMsg = '下载失败: '
          if (error.response) {
            switch (error.response.status) {
              case 404:
                errorMsg += '文件不存在'
                break
              case 403:
                errorMsg += '没有权限下载该文件'
                break
              default:
                errorMsg += error.message || '未知错误'
            }
          } else {
            errorMsg += error.message || '未知错误'
          }
          this.$message.error(errorMsg)
        })
        .finally(() => {
          this.$modal.closeLoading()
        })
    }
  }
}
</script>
